package day11;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author oldliu
 * @since 1.0
 */
public class XMLAdd2 {
    public static void main(String[] args) {
        //从无到有
        SAXReader reader=new SAXReader();
        Document document=null;
        try {
             document = reader.read(new File("课工场76.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
            //!!!!!!!
            document= DocumentHelper.createDocument();
            Element root = document.addElement("javaclass");
            root.addAttribute("name","课工场76班");
            root.addElement("starttime").setText("2021-11-25");
        }
        Scanner input=new Scanner(System.in);

        Element root = document.getRootElement();
        System.out.println("新人学号和性别：");
        String no=input.next();
        String sex=input.next();
        Element newstu = root.addElement("student");
        newstu.addAttribute("sex",sex);
        newstu.addAttribute("no",no);
        System.out.println("Zai 输入姓名年龄和手机号，擅长:");
        String name=input.next();
        int age=input.nextInt();
        String phone=input.next();
        String good=input.next();
        newstu.addElement("name").setText(name);
        newstu.addElement("age").setText(String.valueOf(age));
        newstu.addElement("phone").setText(phone);
        newstu.addElement("goodAt").setText(good);
        //节点更新完成
        //写回xml
        OutputFormat format=OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        try {
            XMLWriter xm=new XMLWriter(new FileWriter("课工场76.xml"),format);
            xm.write(document);
            xm.close();
            System.out.println("xie ru chenggong");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
